package com.source.elasticsearch.utils;

import com.source.elasticsearch.bean.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author wengqy
 * @Date 2021/1/26
 */
public class HtmlParseUtil {


    public List<Content> parseJD(String keywords) throws Exception {
        String url = "https://search.jd.com/Search?keyword=" + keywords;
        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");
        ArrayList<Content> goodsList = new ArrayList<>();
        // 获取京东的商品信息
        for (Element el : elements) {
         //   String img = el.getElementsByTag("img").eq(0).attr("source-data- lazy-img");
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
            // 封装获取的数据
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            goodsList.add(content);
        }
        return goodsList;
    }




    public static void main(String[] args) throws IOException {
// jsoup不能抓取ajax的请求，除非自己模拟浏览器进行请求！
        // 1、https://search.jd.com/Search?keyword=java
        String url = "https://search.jd.com/Search?keyword=js";
        // 2、解析网页（需要联网）
        Document document = Jsoup.parse(new URL(url), 30000);
        // 3、抓取搜索到的数据！
        // Document 就是我们JS的Document对象，你可以看到很多JS语法
        Element element = document.getElementById("J_goodsList");
        // 4、找到所有的li元素
        Elements elements = element.getElementsByTag("li");
        // 获取京东的商品信息
        for (Element el : elements) {
            // 这种网站，一般为了保证效率，一般会延时加载图片
            // String img = el.getElementsByTag("img").eq(0).attr("src");
          //  String img = el.getElementsByTag("p-img").eq(0).attr("source-data- lazy-img");
          //  Elements elementsByTag = el.getElementsByClass("p-img");
            // data-lazy-img
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");

            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();
           System.out.println(img);
            System.out.println(price);
            System.out.println(title);
            System.out.println("================================");
        }
    }
}
